<template>
  <div class="chat-app">
    <header class="chat-header">
      <h1>AI 编程小助手</h1>
      <span class="chat-id">聊天室ID: {{ chatId }}</span>
    </header>
    <main class="chat-history" ref="history">
      <div v-for="msg in messages" :key="msg.id" :class="['msg-row', msg.role]">
        <div class="msg-bubble">
          <div class="msg-content">{{ msg.content }}</div>
        </div>
      </div>
    </main>
    <footer class="chat-footer">
      <input
        v-model="input"
        class="chat-input"
        placeholder="请输入您的问题（如代码疑惑、面试等）"
        :disabled="loading"
        @keyup.enter="sendMsg"
      />
      <button @click="sendMsg" :disabled="loading || !input" class="send-btn">发送</button>
    </footer>
  </div>
</template>

<script>
const SSE_API = 'http://localhost:8081/api/ai/chat';

function generateId() {
  return 'chat-' + Math.random().toString(36).slice(2, 10) + Date.now();
}

export default {
  name: 'App',
  data() {
    return {
      chatId: generateId(),
      messages: [],
      input: '',
      loading: false,
      memoryId: Math.floor(Math.random() * 100000),
    };
  },
  methods: {
    scrollToBottom() {
      this.$refs.history.scrollTop = this.$refs.history.scrollHeight;
    },
    sendMsg() {
      if (!this.input.trim() || this.loading) return;
      const messageText = this.input;
      this.messages.push({
        id: `user-${Date.now()}`,
        role: 'user',
        content: messageText,
      });
      this.input = '';
      this.scrollToBottom();
      this.requestAI(messageText);
    },
    requestAI(userMsg) {
      this.loading = true;
      let responseChunks = '';
      const eventSource = new EventSource(`${SSE_API}?memoryId=${this.memoryId}&message=${encodeURIComponent(userMsg)}`);
      const msgId = `ai-${Date.now()}`;
      const newMsg = { id: msgId, role: 'ai', content: '' };
      this.messages.push(newMsg);
      eventSource.onmessage = (event) => {
        if (event.data) {
          responseChunks += event.data;
          newMsg.content = responseChunks;
          this.$forceUpdate();
          this.scrollToBottom();
        }
      };
      eventSource.onerror = () => {
        eventSource.close();
        this.loading = false;
        this.scrollToBottom();
      };
      eventSource.onopen = () => {};
      eventSource.addEventListener('end', () => {
        eventSource.close();
        this.loading = false;
        this.scrollToBottom();
      });
    },
  },
};
</script>

<style>
body { background: #f4f7fa; }
.chat-app {
  max-width: 550px;
  margin: 32px auto;
  border-radius: 16px;
  box-shadow: 0 4px 24px #0001;
  background: #fff;
  display: flex;
  flex-direction: column;
  height: 84vh;
}
.chat-header {
  padding: 18px 22px 8px 22px;
  border-bottom: 1px solid #f0f0f0;
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.chat-header h1 {
  margin: 0;
  font-size: 1.6rem;
  color: #2268b4;
  font-weight: bold;
}
.chat-id { font-size: 0.92rem; color: #666; }
.chat-history {
  flex: 1;
  overflow-y: auto;
  padding: 30px 13px 16px 13px;
  background: #f7fafc;
}
.msg-row { display: flex; margin-bottom: 16px; }
.msg-row.user { justify-content: flex-end; }
.msg-row.ai { justify-content: flex-start; }
.msg-bubble {
  max-width: 68%;
  padding: 13px 16px;
  border-radius: 15px;
  font-size: 1.1rem;
  box-shadow: 0 3px 10px #2b8be108;
}
.msg-row.user .msg-bubble {
  background: #2b8be1; color: #fff; border-bottom-right-radius: 4px;
}
.msg-row.ai .msg-bubble {
  background: #fff; color: #333; border-bottom-left-radius: 4px; border: 1px solid #e2e2e3;
}
.chat-footer {
  display: flex;
  border-top: 1px solid #f0f0f0;
  padding: 14px 18px;
  background: #fafbfc;
}
.chat-input {
  flex: 1;
  font-size: 1.08rem;
  padding: 9px 13px;
  border: 1px solid #e2e2e3;
  border-radius: 8px;
  margin-right: 9px;
  outline: none;
}
.chat-input:disabled {
  background: #f7f7f9;
}
.send-btn {
  padding: 9px 16px;
  background: #2268b4;
  border: none;
  border-radius: 8px;
  color: #fff;
  font-size: 1rem;
  cursor: pointer;
  transition: background 0.2s;
}
.send-btn:disabled { background: #cccccc; cursor: not-allowed; }
</style>
